// Author: Puyan Lotfi
// Date: Written in June 2009
// Description: Logic Code Related to the editor, abtracted from the GUI code.

#include <QFile>
#include <QIODevice>
#include <QFileInfo>
#include <QStringList>

#include "editorhelpers.h"

EditorHelpers::EditorHelpers() :
        m_currentFilename("Untitled.txt")
{
}

QString EditorHelpers::getCurrentFilename()
{
    return m_currentFilename;
}

void EditorHelpers::resetCurrentFilename()
{
    m_currentFilename = "";
}

QString EditorHelpers::loadFileText(QString filename)
{
    if(!QFile::exists(filename)) return ""; // TODO: Throw an Exception
    m_currentFilename = filename;
    QFile file(m_currentFilename);
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    QString filetext(file.readAll());
    file.close();
    return filetext;
}

void EditorHelpers::saveFileText(QString filetext)
{
    // TODO: Handle any permission related exceptions HERE
    QFile file(m_currentFilename);
    file.open(QIODevice::WriteOnly | QIODevice::Text);
    file.write(filetext.toStdString().c_str(), filetext.length());
    file.close();
}

void EditorHelpers::saveFileText(QString filetext, QString filename)
{
    if(!QFile::exists(filename))
    {
        // Do Nothing
    }

    m_currentFilename = filename;
    saveFileText(filetext);
}

QString EditorHelpers::getCurrentFileExtension()
{
    QStringList tokens = m_currentFilename.split(".", QString::SkipEmptyParts, Qt::CaseSensitive);
    return tokens.last();
}

